package org.example.lys.utils;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author JinHao
 * Date: 2023/04/13 14:12
 * 定制图片生成工具
 */
@Slf4j
public class CustomizeQrCodeUtil {

    private static final int LIMIT_LENGTH = 14;

    /**
     * 生成定制二维码信息图片
     *
     * @param baseImage    背景图
     * @param weChatImage  微信二维码
     * @param shopInfo     门店信息
     * @param positionName 职位信息
     * @return {@link BufferedImage}
     * @throws IOException IOException
     */
    public static BufferedImage createImage(InputStream baseImage, InputStream weChatImage, String shopInfo, String positionName) throws IOException {
        // 文字长度处理
        if (shopInfo.length() > LIMIT_LENGTH) {
            shopInfo = shopInfo.substring(0, LIMIT_LENGTH).concat("***");
        }
        if (positionName.length() > LIMIT_LENGTH) {
            positionName = positionName.substring(0, LIMIT_LENGTH).concat("***");
        }

        // 1.创建图片缓冲区，这里直接将背景图设置成画板
        BufferedImage outImage = ImageIO.read(baseImage);
        // 2.创建画布，获取图像对象
        Graphics2D graphics2D = outImage.createGraphics();
        // 3.抗锯齿，防止模糊
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        hints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        hints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR);
        graphics2D.setRenderingHints(hints);
        // 4.在画布上画上二维码 X轴 Y轴 宽度 高度
        BufferedImage image = ImageIO.read(weChatImage);
        graphics2D.drawImage(image, 180, 210, 448, 448, null);
        // 5.设置文字颜色为灰色
        graphics2D.setColor(Color.gray);
        // 6.设置文字格式
        graphics2D.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 28));
        // 7.填充文字
        graphics2D.drawString(shopInfo, 200, 756);
        graphics2D.drawString(positionName, 200, 824);

        // 关闭流
        baseImage.close();
        weChatImage.close();
        graphics2D.dispose();
        outImage.flush();
        // 返回
        return outImage;
    }
}
